// 盘点客户数量统计报表

import * as React from 'react'
import { useState, useEffect } from 'react'
import moment from 'moment'
import { timeToString, toDateString } from '../helper'
import apis from '@/apis/Report'
import './index.scss'
import { Button, Col, Form, Row, DatePicker, Table, Select, Spin, message } from 'antd'
import { http } from '@/lib'
import { downBlobFile } from '@/utils/methods'
const { RangePicker } = DatePicker
const { Option } = Select
// 搜索框
function SearchBar(props) {
  const { changeFatherDataSource } = props
  const [searchValue, setSearchValue] = useState(props.searchValue)
  // 保存销售组织列表
  const [brandList, setBrandList] = useState<any>([])
  // 销售组织列表加载状态
  const [selectLoading, setSelectLoading] = useState(false)
  // 表单点击查询时候执行的方法
  const onSubmit = e => {
    e.preventDefault()
    if (searchValue.checkTime.length === 0) {
      message.warn('盘点周期必选')
      return
    }
    sessionStorage.setItem('searchValueForStock', JSON.stringify(searchValue))
    // 这里应当不请求数据，而是通过传递searchValue来调用父组件中的方法，以实现查询数据。
    changeFatherDataSource(searchValue)
  }
  // 获取销售组织列表
  useEffect(() => {
    let UaaSysInfo = JSON.parse(sessionStorage.getItem('UaaSysInfo'))
    setBrandList(UaaSysInfo.profile.brandList)
    // 获取session中存储的筛选条件,如果有则直接读取
    let se = sessionStorage.getItem('searchValueForStock')
      ? JSON.parse(sessionStorage.getItem('searchValueForStock'))
      : ''
    let flag = false
    if (se) {
      if (se.checkTime.length > 0) {
        se.checkTime[0] = se.checkTime[0] && moment(se.checkTime[0])
        se.checkTime[1] = se.checkTime[1] && moment(se.checkTime[1])
      }
      setSearchValue(se)
      for (let key in se) {
        // console.log(se[key]);
        if ((!(se[key] instanceof Array) && se[key] !== '') || (se[key] instanceof Array && se[key].length > 0)) {
          // console.log(se[key]);
          flag = true
        }
      }
      setTimeout(() => {
        flag && changeFatherDataSource(se)
      }, 0)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  const [mode, setMode] = useState(['month', 'month'])
  return (
    <div className="search-bar-form">
      <Form layout="inline" name="formValue" onSubmit={onSubmit}>
        <Row>
          <Col offset={1} span={7}>
            <Form.Item label="销售组织">
              {/* 这是一个下拉选 */}
              <Select
                placeholder="请选择销售组织"
                onChange={(values: any) => {
                  setSearchValue({ ...searchValue, brandCode: values })
                }}
                style={{ width: '174px', color: searchValue.brandCode == '' ? '#ccc' : '' }}
                allowClear={true}
                loading={selectLoading}
                disabled={selectLoading}
                value={searchValue.brandCode != '' ? searchValue.brandCode : '请选择销售组织'}
                dropdownMatchSelectWidth={false}
              >
                {brandList.map(({ brandCode, brandName }) => (
                  <Option style={{ width: '250px' }} key={brandCode} value={brandCode}>
                    {brandName}
                  </Option>
                ))}
              </Select>
            </Form.Item>
          </Col>
          <Col offset={1} span={7}>
            <Form.Item label="盘点周期" required={true}>
              <RangePicker
                placeholder={['开始日期', '结束日期']}
                value={searchValue.checkTime}
                onChange={value => {
                  setSearchValue({ ...searchValue, checkTime: value || [] })
                }}
                onOpenChange={status => {
                  if (status) {
                    setSearchValue({ ...searchValue, checkTime: [] })
                  }
                }}
                disabledDate = {(_current) => {
                  let current = _current.format('YYYY-MM-DD')
                  return current && current > moment().endOf('day').format('YYYY-MM-DD')
                }}
                // onPanelChange={(value, mode) => {
                //   // 判断选择的日期是否超过了今天
                //   if ((value[0] as any) > moment.now() || (value[1] as any) > moment.now()) {
                //     message.warn('选择的日期不能超过当月')
                //   } else {
                //     setSearchValue({ ...searchValue, checkTime: value || [] })
                //     setMode([mode[0] === 'date' ? 'month' : mode[0], mode[1] === 'date' ? 'month' : mode[1]])
                //   }
                // }}
                style={{ width: '220px' }}
                format="YYYY-MM-DD"
              />
            </Form.Item>
          </Col>
        </Row>
        <Row
          align="middle"
          justify="space-around"
          gutter={24}
          style={{
            marginTop: '20px',
            borderTop: '1px solid #eee',
            borderBottom: '1px solid #eee',
            paddingTop: '4px',
            paddingBottom: '4px',
          }}
        >
          <Col offset={10} span={14}>
            <Button htmlType="submit" type="primary" style={{ marginRight: '20px' }}>
              查询
            </Button>
            <Button
              type="default"
              onClick={() => {
                setSearchValue({
                  // 销售组织
                  brandCode: '',
                  // 管理区域
                  belongAreaName: '',
                  // 盘点周期 -> 盘点开始时间inventoryBegineTime  盘点结束时间inventoryEndTime
                  checkTime: [],
                })
                sessionStorage.removeItem('searchValueForStock')
              }}
            >
              重置
            </Button>
          </Col>
        </Row>
      </Form>
    </div>
  )
}

const FormSearchBar = Form.create({ name: 'searchBar' })(SearchBar) as any

const StockCustomerCountReport = props => {
  // 设置已盘点客户数量合未盘点客户数量的ui样式
  const spanUI = { color: 'blue', cursor: 'pointer' } as any
  // 设置父tabletitle样式
  // const fatherTableTitleStyle = {fontWeight:'bolder', color:'#000'} as any
  const fatherTableTitleStyle = {} as any
  const [searchValue, setSearchValue] = useState({
    // 销售组织
    brandCode: '',
    // 管理区域
    belongAreaName: '',
    // 盘点周期 -> 盘点开始时间inventoryBegineTime  盘点结束时间inventoryEndTime
    checkTime: [],
  })
  // 父table的 已盘点客户数量 和 未盘点客户数量的点击事件
  const onFatherTableSpanClick = (goWhere, record) => {
    // goWhere 是一个布尔值，如果为true则进入已盘点客户数量列表，如果为false则进入未盘点客户数量列表
    // let ITime = toDateString(searchValue.checkTime[0].format('YYYY-MM'), searchValue.checkTime[1].format('YYYY-MM'));
    record.inventoryTime = record.inventoryTimeExcel
    if (goWhere === true) {
      // 进入已盘点客户数量详情列表，并将record保存起来
      sessionStorage.setItem('stateForCheckedCustomerList', JSON.stringify(record))
      props.history.push({
        pathname: `/report/stockcustomercountreport/checkedcustomerlist/${record.inventoryCustomerBeanListVo?.belongAreaCode}`,
        state: { record },
      })
    } else {
      // 进入未盘点客户数量详情列表
      sessionStorage.setItem('stateForCheckedCustomerList', JSON.stringify(record))
      props.history.push({
        pathname: `/report/stockcustomercountreport/notcheckedcustomerlist/${record.inventoryCustomerBeanListVo?.belongAreaCode}`,
        state: { record },
      })
    }
  }
  // 父表格的columns
  const columns = [
    {
      title: <span style={fatherTableTitleStyle}>销售组织</span>,
      dataIndex: 'brandName',
      key: 'brandName',
      align: 'center',
    },
    {
      title: <span style={fatherTableTitleStyle}>管理区域</span>,
      dataIndex: 'belongAreaName',
      key: 'belongAreaName',
      align: 'center',
    },
    {
      title: <span style={fatherTableTitleStyle}>盘点周期</span>,
      dataIndex: 'inventoryTimeExcel',
      key: 'inventoryTimeExcel',
      align: 'center',
    },
    {
      title: <span style={fatherTableTitleStyle}>审批通过数量</span>,
      dataIndex: 'hasNumberPlate',
      key: 'hasNumberPlate',
      align: 'center',
      // 点击数字进行跳转到详情页，查询指定销售组织的已盘点客户数量
      render: (text, record) => {
        return (
          <span
            style={spanUI}
            onClick={() => {
              onFatherTableSpanClick(true, record)
            }}
          >
            {text}
          </span>
        )
      },
    },
    {
      title: <span style={fatherTableTitleStyle}>审批中数量</span>,
      dataIndex: 'underApprovalNumber',
      key: 'underApprovalNumber',
      align: 'center',
    },
    {
      title: <span style={fatherTableTitleStyle}>审批不通过数量</span>,
      dataIndex: 'approvalFailedNumber',
      key: 'approvalFailedNumber',
      align: 'center',
    },
    {
      title: <span style={fatherTableTitleStyle}>未盘点客户数量</span>,
      dataIndex: 'noNumberPlate',
      key: 'noNumberPlate',
      align: 'center',
      // 点击数字进行跳转到详情页，查询指定销售组织未盘点客户数量
      render: (text, record) => {
        return (
          <span
            style={spanUI}
            onClick={() => {
              onFatherTableSpanClick(false, record)
            }}
          >
            {text}
          </span>
        )
      },
    },
  ]
  // 父表格的loading
  const [loading, setLoading] = useState(false)
  // 父表格的pagination
  const [pagination, setPagination] = useState({
    page: 1,
    current: 1,
    pageSize: 10,
    showSizeChanger: true,
    showQuickJumper: true,
    pageSizeOptions: ['10', '20', '40', '60', '100', '150', '200'],
    total: 0,
    showTotal: (total, range) => `当前${range[0]}-${range[1]},共${total}项`,
  })
  // 父表格的数据源
  const [dataSource, setDataSource] = useState([])
  // 使用变量记录已盘点的客户数量
  const [checkedCustomerCount, setCheckedCustomerCount] = useState<any>('--')
  // 使用变量记录未盘点的客户数量
  const [notCheckedCustomerCount, setNotCheckedCustomerCount] = useState<any>('--')
  // 导出按钮的loading
  const [exportLoading, setExportLoading] = useState(false)
  const [search, setSearch] = useState(false)
  const changeFatherDataSource = searchValue => {
    // 设置好父页面的搜索值
    setSearchValue(searchValue)
    // 如果父页面的当前的页码为1，则说明需要额外的发送请求
    // if (pagination.page === 1) {
    setSearch(!search)
    // }
    setPagination({ ...pagination, page: 1, current: 1 })
  }
  // 点击查询显示等待
  const changeSpinning = () => {
    setLoading(true)
  }
  // 进入页面的时候加载数据
  useEffect(() => {
    sessionStorage.removeItem('stateForCheckedCustomerList')
    sessionStorage.removeItem('inventoryCycle')
    sessionStorage.removeItem('hasNumberPlateList')
    sessionStorage.removeItem('noNumberPlateList')
    // 离开界面的时候，判断url中是否包含stockcustomercountreport，如果包含则不用清除搜索的值
    return () => {
      if (props.history.location.pathname.indexOf('stockcustomercountreport') === -1) {
        sessionStorage.removeItem('searchValueForStock')
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
  const [firstCome, setFirstCome] = useState(true)
  useEffect(() => {
    if (!firstCome) {
      fetchFatherTableData()
    }
    firstCome && setFirstCome(false)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [search])
  // 加载父table的数据
  const fetchFatherTableData = () => {
    setLoading(true)
    setExportLoading(true)
    let request: any = {
      page: pagination.page,
      size: pagination.pageSize,
    }
    let t: any = []
    // if (searchValue.checkTime.length > 0) {
    //   t = toDateString(searchValue.checkTime[0].format('YYYY-MM-DD'), searchValue.checkTime[1].format('YYYY-MM-DD'))
    // }
    if (searchValue.belongAreaName) {
      request.belongAreaName = searchValue.belongAreaName
    }
    if (searchValue.brandCode) {
      request.brandCode = searchValue.brandCode
    }
    if (searchValue.checkTime.length > 0) {
      request.inventoryBegineTime = `${searchValue.checkTime[0].format('YYYY-MM-DD')} 00:00:00`
      request.inventoryEndTime = `${searchValue.checkTime[1].format('YYYY-MM-DD')} 23:59:59`
    }
    http
      .post(apis.InventoryCustomerNumber, request)
      .then(res => {
        let data = res.data.content[0].inventoryCustomerNumberVos
        data.forEach((item, index) => {
          item.key = index
        })

        setDataSource(res.data.content[0].inventoryCustomerNumberVos)
        setCheckedCustomerCount(res.data.content[0].hasNumberPlate)
        setNotCheckedCustomerCount(res.data.content[0].noNumberPlate)
        setPagination({ ...pagination, total: res.data.totalElements })
        setLoading(false)
        setExportLoading(false)
      })
      .catch(() => {
        setLoading(false)
        setExportLoading(false)
      })
  }
  // 导出盘点客户数量统计
  /**
   * @param type 1，2，3分别代表导出全部，导出已盘点，导出未盘点
   */
  const exportCustomerCountDetailExcel = (type: number) => {
    let t: any = []
    if (searchValue.checkTime.length === 0) {
      message.warn('请选择盘点周期')
      return
    }
    let url: string = ''
    let fileName: string = ''
    let param: string = `?page=${1}&size=${30000}`
    for (let key in searchValue) {
      if (searchValue[key] && !(searchValue[key] instanceof Array)) {
        param += `&${key}=${searchValue[key]}`
      } else if (searchValue[key] instanceof Array && searchValue[key].length > 0) {
        // let start = searchValue[key][0].format('YYYY-MM')
        // let end = searchValue[key][1].format('YYYY-MM')
        t = [`${searchValue.checkTime[0].format('YYYY-MM-DD')} 00:00:00`, `${searchValue.checkTime[1].format('YYYY-MM-DD')} 23:59:59`]
        param += `&inventoryBegineTime=${searchValue.checkTime[0].format('YYYY-MM-DD')} 00:00:00&inventoryEndTime=${searchValue.checkTime[1].format('YYYY-MM-DD')} 23:59:59`;
      }
    }
    if (type === 1) {
      setExportLoading(true)
      message.warn('导出中....请稍等')
      // 导出统计报表,get请求
      url = apis.InventoryCustomerNumberExcel
      fileName = '盘点客户数量统计报表'
      http
        .get(url + param, { responseType: 'arraybuffer', timeout: 1000 * 60 * 10 * 1000 })
        .then(res => {
          downBlobFile(res.data, fileName)
          setExportLoading(false)
          message.success('导出成功')
        })
        .catch(() => {
          setExportLoading(false)
          message.error('导出失败')
        })
    } else if (type === 2 || type === 3 || type === 4 || type === 5) {
      let request: any = {
        page: 1,
        size: 30000,
        inventoryBegineTime: t[0],
        inventoryEndTime: t[1],
        // 不传管理区域
        // belongAreaCode: dataSource[0]?.inventoryCustomerBeanListVo?.belongAreaCode
      }

      //fileName = type === 2 ? `已盘点客户明细` : `未盘点客户明细`;
      let str = timeToString(searchValue.checkTime[0].format('YYYY-MM'), searchValue.checkTime[1].format('YYYY-MM'))
      if (type === 2) {
        fileName = '审批通过客户明细'
        // request.hasNumberPlateList = hasNumberPlateList;
        request.hasNumberPlateList = ['Y']
        // 传递时间区间字符串

        request.inventoryCycle = str
      } else if (type === 3) {
        fileName = '未盘点客户明细'
        // 未盘点只能选择一个周期
        // if (str.split(',').length > 1) {
        //     message.error("导出未盘点客户明细只允许选择一个月周期!");
        //     return;
        // }
        request.inventoryCycle = str
        // request.noNumberPlateList = noNumberPlateList;
        request.noNumberPlateList = ['Y']
      } else if (type === 4) {
        fileName = '审批中客户明细'
        // request.hasNumberPlateList = hasNumberPlateList;
        request.underApprovalList = ['Y']
        // 传递时间区间字符串

        request.inventoryCycle = str
      } else if (type === 5) {
        fileName = '审批不通过客户明细'
        // request.hasNumberPlateList = hasNumberPlateList;
        request.approvalFailedList = ['Y']
        // 传递时间区间字符串

        request.inventoryCycle = str
      }
      message.warn('导出中....请稍等')
      setExportLoading(true)
      // 传递brandCode
      if (searchValue.brandCode) {
        request.brandCode = searchValue.brandCode
      }

      // post请求，将dataSource中的所有noNumberPlateList做成一个数组，所有hasNumberPlateList做成一个数组
      http
        .post(apis.InOrderToInventoryListExcel, request, { responseType: 'arraybuffer' })
        .then(res => {
          message.success('导出成功')
          downBlobFile(res.data, fileName)
          setExportLoading(false)
        })
        .catch(() => {
          setExportLoading(false)
        })
    }
  }
  // 修改已盘点客户数量总数和未盘点客户数量总数的方法
  const changeCustomerCount = (checkedCustomerCount, notCheckedCustomerCount) => {
    setCheckedCustomerCount(checkedCustomerCount)
    setNotCheckedCustomerCount(notCheckedCustomerCount)
  }
  return (
    <React.Fragment>
      <div className="StockCustomerCountReport1-title">盘点客户数量统计报表</div>
      <FormSearchBar
        searchValue={searchValue}
        changeFatherDataSource={changeFatherDataSource}
        changeSpinning={changeSpinning}
        changeCustomerCount={changeCustomerCount}
      />
      {/* <div className="export-div"> */}
      <Spin spinning={exportLoading}>
        <div style={{ marginTop: '10px', marginBottom: '10px' }}>
          <Button
            type="primary"
            className="btn-shape"
            onClick={() => {
              // 导出盘点客户数量统计
              setTimeout(() => {
                exportCustomerCountDetailExcel(1)
              }, 0)
            }}
          >
            导出
          </Button>
          <Button
            type="primary"
            className="btn-shape"
            style={{ borderLeft: '1px solid #fff' }}
            onClick={() => {
              // 导出盘点客户数量统计
              setTimeout(() => {
                exportCustomerCountDetailExcel(2)
              }, 0)
            }}
          >
            导出审批通过客户明细
          </Button>
          <Button
            type="primary"
            className="btn-shape"
            style={{ borderLeft: '1px solid #fff' }}
            onClick={() => {
              // 导出盘点客户数量统计
              setTimeout(() => {
                exportCustomerCountDetailExcel(4)
              }, 0)
            }}
          >
            导出审批中客户明细
          </Button>
          <Button
            type="primary"
            className="btn-shape"
            style={{ borderLeft: '1px solid #fff' }}
            onClick={() => {
              // 导出盘点客户数量统计
              setTimeout(() => {
                exportCustomerCountDetailExcel(5)
              }, 0)
            }}
          >
            导出审批不通过客户明细
          </Button>
          <Button
            type="primary"
            style={{ borderLeft: '1px solid #fff' }}
            className="btn-shape"
            onClick={() => {
              // 导出盘点客户数量统计
              setTimeout(() => {
                exportCustomerCountDetailExcel(3)
              }, 0)
            }}
          >
            导出未盘点客户明细
          </Button>
        </div>
      </Spin>
      {/* </div> */}
      <div className="StockCustomerCountReport-total">
        <span className="total">合计:</span> 已盘点客户数量 {loading ? '--' : <span>{checkedCustomerCount}</span>}
        ，未盘点客户数量 {loading ? '--' : <span>{notCheckedCustomerCount}</span>}
      </div>
      {/* 父表格 */}
      <Spin spinning={loading}>
        <Table
          // 父table的columns
          columns={columns as any}
          // 父table的pagination
          pagination={pagination}
          // 父table的数据源
          dataSource={dataSource}
          // 父table的onChange事件
          onChange={pageOptions => {
            setPagination({
              ...pagination,
              pageSize: pageOptions.pageSize,
              current: pageOptions.current,
              page: pageOptions.current,
            })
          }}
          // 父table的展开行触发的事件
        />
      </Spin>
    </React.Fragment>
  )
}
export default StockCustomerCountReport
